﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;

namespace Marmat.Forms.Design
{
    /// <summary>
    /// 设计支持
    /// </summary>
    public sealed class DesignSupport
    {
        private static bool _initializeed = false;

        /// <summary>
        /// 在设计模式下初始化服务。
        /// </summary>
        /// <param name="component"></param>
        public static void InitializeService(ComponentDesigner component)
        {
            if (component is null)
                throw new ArgumentNullException(nameof(component));
            DesignSupport.InitializeService(component.Component);
        }


        /// <summary>
        /// 在设计模式下初始化服务。
        /// </summary>
        /// <param name="component"></param>
        public static void InitializeService(System.ComponentModel.IComponent component)
        {
            if (component is null)
                throw new ArgumentNullException(nameof(component));
            IDesignerHost designer = (IDesignerHost)component.Site.GetService(typeof(IDesignerHost));
            DesignSupport.InitializeService(designer);
        }

        /// <summary>
        /// 在设计模式下初始化服务。
        /// </summary>
        /// <param name="designer"></param>
        public static void InitializeService(IDesignerHost designer)
        {
            if (designer is null)
                throw new ArgumentNullException(nameof(designer));
            if (_initializeed == true)
                return;
            Type type = designer.GetType(designer.RootComponentClassName);
            if (type is null)
                throw new NullReferenceException($"构建设计实例失败,可能需要重新生成当前项目.");
            System.Reflection.Assembly assembly = type.Assembly;
            foreach (var item in assembly.GetExportedTypes())
            {
                if (item.GetInterfaces().FirstOrDefault(x => x == typeof(IDesignSupport)) != null)
                {
                    _initializeed = true;
                    IDesignSupport support = (IDesignSupport)assembly.CreateInstance(item.FullName);
                    support.InitializeService();
                }
            }
        }
    }
}
